package com.kason.framework.factory;

import com.kason.framework.Invocation;
import com.kason.framework.LoadBalance;
import com.kason.framework.Protocol;
import com.kason.framework.Remote;
import com.kason.framework.regester.ZookeeperRegester;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author 卢清波
 * @date 2021/2/19 19:06
 */
public class ProxyFactory
{
    public static <T> T getProxy(final Class interfaceClass){
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler()
        {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable
            {

                Invocation invocation = new Invocation();
                invocation.setInterfaceName(interfaceClass.getName());
                invocation.setMethodName(method.getName());
                invocation.setArgTypes(method.getParameterTypes());
                invocation.setArgs(objects);
                // 远程获取注册服务
                List<Remote> remotes = ZookeeperRegester.get(interfaceClass.getName());
                // Remote remote = remotes.get(0);
                // 负载均衡--随机
                Remote random = LoadBalance.random(remotes);
                Protocol protocol = ProtocolFactory.getProtocol();
                String send = protocol.send(random, invocation);
                return send ;
            }
        });


    }
}
